#!/bin/bash

echoRed() { echo $'\e[0;31m'"$1"$'\e[0m'; }
echoGreen() { echo $'\e[0;32m'"$1"$'\e[0m'; }
echoYellow() { echo $'\e[0;33m'"$1"$'\e[0m'; }

#切换到脚本目录
cd "$(dirname "$0")"  || { echoRed "cannot cd $0"; exit 1; }
#获取当前目录
workdir=`pwd -P`
#echo "workdir= $workdir"
#获取文件全路径
filename=$(basename "$0")
#获取文件后缀
if [[ "${filename##*.}" == "jar" ]] ; then
  mode=0
else
  mode=1
fi
#echo "mode= $mode"
configfile="$workdir/${filename%.*}.conf"
if [[ -e ${configfile} ]] ; then
  ! [[ -r "$configfile" ]] && { echoRed "$configfile can not read."; exit 1; }
  source "${configfile}"
else
  echoYellow "config(${configfile}) not found."
  #exit 1
fi

if [[ $mode == 0 ]]; then
  jarfile=$workdir/$filename
else
  [[ -n "$jarName" ]] && jarfile="$workdir/${jarName}"
  [[ -z "$jarName" ]] && jarfile="$workdir/${filename%.*}.jar"
fi
! [[ -e "$jarfile" ]] && { echoRed "jarfile(${jarfile}) does not exist."; exit 1; }
[[ -z "$PID_FOLDER" ]] && PID_FOLDER=$workdir
[[ -z "$LOG_FOLDER" ]] && LOG_FOLDER=$workdir
[[ "$DEBUG" == true ]] && set -x
[[ -z "$APP_NAME" ]] && APP_NAME=${filename%.*}
[[ -z "$STOP_WAIT_TIME" ]] && STOP_WAIT_TIME=10

if [[ -n "$JAVA_HOME" ]] ; then
    javaexe="$JAVA_HOME/bin/java"
    ! [[ -x "$javaexe" ]] && { echoRed "$javaexe non-executable."; exit 1; }
elif type -p java > /dev/null 2>&1; then
    javaexe=$(type -p java)
elif [[ -x "/usr/bin/java" ]];  then
    javaexe="/usr/bin/java"
else
    echo "Unable to find Java"
    exit 1
fi

#echo "find java: $javaexe"

pid_file="$PID_FOLDER/${APP_NAME}.pid"
log_file="$LOG_FOLDER/${APP_NAME}-startup.log"

getpid(){
  pid=`ps ax | grep -i ${jarfile} | grep java | grep -v grep | awk '{print $1}'`
}

pidIsExist() {
  ps -p "$1" &> /dev/null
}

isRunning() {
  getpid
  if [ -z ${pid} ] ; then
    return 1
  else
    return 0
  fi
}
start(){
  getpid
  if [ -z ${pid} ] ; then
    do_start
  else
    echoYellow "${APP_NAME} is already running ($pid)."
    return 0
  fi
}
do_start() {
  #丢弃输出    > /dev/null
  #输出到日志  > start.out
  #echo $! > pid
  #执行启动命令
  arguments="${JAVA_OPTS} -jar ${jarfile} ${RUN_ARGS}"
  nohup ${javaexe} ${arguments} > ${log_file} 2>&1 &
  pid=$!
  #echo "$pid" > "$pid_file"
  pidIsExist "$pid" && { echoGreen "${APP_NAME} started ($pid)."; return 0; }
  echoRed "${APP_NAME} started error.";
  return 1;
}
check_start(){
  for ((i = 1; i <= 3; i++)); do
     isRunning || { echoRed "${APP_NAME} started error."; return 1; }
     sleep 1
     echo "check ${APP_NAME} running ${i}s ..."
  done

  echoGreen "${APP_NAME} running ok ($pid)."
  return 0
}

wait_start(){
  #等待启动
  startNum=0 # 记录等待次数
  while [ -z ${pid} ]
  do
    sleep 1
    startNum=`expr $startNum + 1`
    echo "${APP_NAME} starting ${startNum}s ..."
    getpid

    if [ "$startNum" -ge "$STOP_WAIT_TIME" ];then
      #给pid赋值可以结束循环
      pid=1
    fi
  done

  #输出启动结果，因为可能会被赋值重新获取pid
  getpid
  if [ -z ${pid} ] ; then
       echoRed "${APP_NAME} start failed."; return 1;
  else
       echoGreen "${APP_NAME} started ($pid)."; return 0;
  fi
}
stop(){
  getpid
  #是否在运行
  if [ -z ${pid} ] ; then
    echo "${APP_NAME} was not running."
    return 0;
  fi
  #停止服务
  echo "kill ${APP_NAME} (${pid})."
  kill ${pid} &> /dev/null
  #等待kill没有效果，去掉
  #kpid=$!
  #wait $kpid

  for ((i = 1; i <= STOP_WAIT_TIME; i++)); do
      isRunning || { echoGreen "Stopped ${APP_NAME}."; return 0; }
      [[ $i -eq STOP_WAIT_TIME/2 ]] && kill $pid &> /dev/null
      sleep 1
      echo "waiting ${APP_NAME} stop ${i}s ..."
  done

  do_force_stop $pid
}
do_force_stop() {
  echo "force kill ${APP_NAME} (${pid})."
  kill -9 "$1" &> /dev/null

  for ((i = 1; i <= STOP_WAIT_TIME/2; i++)); do
    isRunning || { echoGreen "Stopped ${APP_NAME}."; return 0; }
    sleep 1
  done

  isRunning && { echoRed "failed to stop ${APP_NAME}."; return 1; };
  return 0;
}
status() {
    getpid
    if [ -z ${pid} ] ; then
      echo "${APP_NAME} is not running."
      #exit 0
    else
      echoGreen "${APP_NAME} is running ($pid)."
      #exit 0
    fi
    return 0
}
restart() {
  stop && start
}

case "$1" in

    'start')
        start "$@"; exit $?;;

    'stop')
        stop
        ;;

    'restart')
        restart "$@"; exit $?;;

    'status')
        status
        ;;

    *)
        echo "Usage: $0 { start | stop | restart | status }"
        exit 1
        ;;
esac

exit 0
